package com.ruoyi.mall.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.mall.domain.GoodsCategory;
import com.ruoyi.mall.domain.GoodsCategoryTree;
import com.ruoyi.mall.service.GoodsCategoryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商品类目
 *
 * @author www.joolun.com
 * @date 2019-08-12 11:46:28
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/goodscategory")
public class GoodsCategoryController extends BaseController {

    private final GoodsCategoryService goodsCategoryService;

    /**
    * 分页查询
    * @param page 分页对象
    * @param goodsCategory 商品类目
    * @return
    */
    @GetMapping("/page")
    @SaCheckPermission("mall:goodscategory:index")
    public R<IPage<GoodsCategory>> getGoodsCategoryPage(Page<GoodsCategory> page, GoodsCategory goodsCategory) {
        return R.ok(goodsCategoryService.page(page,Wrappers.query(goodsCategory)));
    }

	/**
	 *  返回树形集合
	 * @return
	 */
	@GetMapping("/tree")
    @SaCheckPermission("mall:goodscategory:index")
	public R<List<GoodsCategoryTree>> getGoodsCategoryTree() {
		return R.ok(goodsCategoryService.selectTree(null));
	}

    /**
    * 通过id查询商品类目
    * @param id
    * @return R
    */
    @GetMapping("/{id}")
    @SaCheckPermission("mall:goodscategory:get")
    public R<GoodsCategory> getById(@PathVariable("id") String id){
        return R.ok(goodsCategoryService.getById(id));
    }

    /**
    * 新增商品类目
    * @param goodsCategory 商品类目
    * @return R
    */
    @PostMapping
    @SaCheckPermission("mall:goodscategory:add")
    public R<Void> save(@RequestBody GoodsCategory goodsCategory){
        return toAjax(goodsCategoryService.save(goodsCategory));
    }

    /**
    * 修改商品类目
    * @param goodsCategory 商品类目
    * @return R
    */
    @PutMapping
    @SaCheckPermission("mall:goodscategory:edit")
    public R<Void> updateById(@RequestBody GoodsCategory goodsCategory){
    	if(goodsCategory.getId().equals(goodsCategory.getParentId())){
			return R.fail("不能将本级设为父类");
		}
        return toAjax(goodsCategoryService.updateById(goodsCategory));
    }

    /**
    * 通过id删除商品类目
    * @param id
    * @return R
    */
    @DeleteMapping("/{id}")
    @SaCheckPermission("mall:goodscategory:del")
    public R<Void> removeById(@PathVariable String id){
        return toAjax(goodsCategoryService.removeById(id));
    }

}
